<?php
namespace Admin\Controller;
use Common\Controller\AdminbaseController;
class BackupController extends AdminbaseController
{
	private $ds = "\n\r\n\r";
	// 每条sql语句的结尾符
	public $sqlEnd = ";";
	public function index() {
		$M = M ();
		$tabs = $M->query ( 'SHOW TABLE STATUS' );
		$total = 0;
		foreach ( $tabs as $k => $v ) {
			$tabs [$k] ['size'] = byteFormat ( $v ['Data_length'] + $v ['Index_length'] );
			$total += $v ['Data_length'] + $v ['Index_length'];
		}
		// echo ."/Public/data/";
		// echo $this->export($tablename="");
		// echo
		// $this->restore("./Public/backup/20130704091642_tao_group_v1.sql");
		$this->assign ( "list", $tabs );
		
		$this->assign ( "total", byteFormat ( $total ) );
		$this->assign ( "tables", count ( $tabs ) );
		$this->display ();
	}
	
	/**
	 * 数据库备份
	 * 参数：备份哪个表(可选),备份目录(可选，默认为backup),分卷大小(可选,默认2048，即2M)
	 *
	 * @param string $dir        	
	 * @param int $size        	
	 * @param array $tablename        	
	 */
	public function export() {
		set_time_limit ( 0 );
		
		$tables = $_POST ['tables'];
		
		$randomstr = rand_string ( 6 );
		$dir = C ( "DB_BACKUP" );
		
		$dir .= "lap_" . date ( 'YmdHis' ) . "_" . $randomstr;
		
		// 文件名前缀
		$filename = "lap_" . date ( 'YmdHis' ) . "_" . $randomstr;
		// 分卷标识
		// 第几分卷
		$p = 1;
		
		$size = $_REQUEST ['sizelimit'];
		if (! $size) {
			$this->error ( "请填写备份文件分卷大小" );
		}
		
		if (empty ( $tables )) {
			$this->error ( "请选择要备份的表" );
		}
		
		$sql = '';
		$M = M ();
		
		// 插入文件头信息
		$sql = $this->_base ();
		
		foreach ( $tables as $value ) {
			
			// 插入表结构信息
			$sql .= $this->_insert_table_structure ( $value );
			
			$M = M ();
			$fields = $M->query ( 'select * FROM `' . $value . '`' );
			
			foreach ( $fields as $data ) {
				
				$sql .= $this->_insert_record ( $value, $data );
				
				if (strlen ( $sql ) >= $size * 1024) {
					$file = $filename . "_" . $p . ".sql";
					
					if ($this->_write_file ( $sql, $file, $dir )) {
						$msg .= "卷-" . $p . '数据备份完成<br />';
					} else {
						$this->error ( "备份表-" . $value . "-失败<br />" );
					}
					
					$p ++;
					
					$sql = "";
				}
			}
		}
		
		if ($sql != "") {
			$file = $filename . "_" . $p . ".sql";
			
			if ($this->_write_file ( $sql, $file, $dir )) {
				$msg .= "卷-" . $p . '数据备份完成<br />';
				$msg .= "全部完成";
			} else {
				
				$this->error ( "备份表-" . $value . "-失败<br />" );
			}
		}
		
		$this->success ( $msg );
	}
	
	// 恢复数据库
	public function import() {
		import ( 'Folder' );
		
		$dir = C ( "DB_BACKUP" );
		
		$files = \Folder::read ( $dir );
		
		$filedb = array ();
		foreach ( $files as $v ) {
			if (preg_match ( '/^lap_(\d{14})_[a-zA-Z0-9]{5}/i', $v, $match )) {
				
				$bk ['name'] = $v;
				$time = explode ( ',', wordwrap ( $match [1], 2, ',', true ) );
				$bk ['time'] = $time [0] . $time [1] . '-' . $time [2] . '-' . $time [3] . ' ' . $time [4] . ':' . $time [5];
				$filedb [] = $bk;
			}
		}
		$filedb = array_reverse ( $filedb );
		$this->assign ( "list", $filedb );
		$this->display ();
	}
	
	/**
	 * 导入备份数据
	 * 说明：分卷文件格式20120516211738_all_1.sql
	 * 参数：文件路径(必填)
	 *
	 * @param string $sqlfile        	
	 */
	function restore() {
		$file = $_REQUEST ['file'];
		
		$sqldir = C ( "DB_BACKUP" ) . $file;
		
		// 检测文件是否存在
		if (! file_exists ( $sqldir ) || ! preg_match ( '/^lap_(\d{14})_[a-zA-Z0-9]{5}/i', $file )) {
			
			$this->error ( "文件不存在！请检查" );
		}
		$this->lock ( C ( "DB_NAME" ) );
		
		$volume_id = 1;
		// 当前分卷为$volume_id
		
		while ( $volume_id ) {
			$tmpfile = $sqldir . "/" . $file . "_" . $volume_id . ".sql";
			
			// 存在其他分卷，继续执行
			if (file_exists ( $tmpfile )) {
				// 执行导入方法
				
				if ($this->_import ( $tmpfile )) {
				} else {
					$volume_id = $volume_id ? $volume_id : 1;
					
					$this->error ( "导入分卷：<span style='color:#f00;'>" . $tmpfile . '</span>失败！可能是数据库结构已损坏！请尝试从分卷1开始导入' );
				}
			} else {
				
				$this->error ( "此分卷备份全部导入成功！<br />" );
			}
			$volume_id ++;
		}
		

	}
	
	/**
	 * 批量删除备份
	 *
	 * @return void
	 */
	public function batchdelete() {
		import ( 'Folder' );
		$dir = C ( "DB_BACKUP" );
		$files = $_REQUEST ['files'];
		if (empty ( $files )) {
			$this->error ( "请选择要删除的备份" );
		}
		
		foreach ( $files as $value ) {
			
			if (! \Folder::rm ( $dir . $value, true )) {
				
				$this->error ( "删除备份" . $value . "出错" );
			}
			;
		}
		
		$this->success ( "删除备份成功" );
	}
	
	/**
	 * 插入数据库备份基础信息
	 *
	 * @return string
	 */
	private function _base() {
		$value = '';
		$value .= '-- MySQL database dump' . $this->ds;
		$value .= '-- Created by DBAction class, Power By TaoTao. ' . $this->ds;
		$value .= '-- http://blog.kisscn.com ' . $this->ds;
		$value .= '--' . $this->ds;
		$value .= '-- 主机: ' . $this->host . $this->ds;
		$value .= '-- 生成日期: ' . date ( 'Y' ) . ' 年  ' . date ( 'm' ) . ' 月 ' . date ( 'd' ) . ' 日 ' . date ( 'H:i' ) . $this->ds;
		$value .= '-- MySQL版本: ' . mysql_get_server_info () . $this->ds;
		$value .= '-- PHP 版本: ' . phpversion () . $this->ds;
		$value .= $this->ds;
		$value .= '--' . $this->ds;
		$value .= '-- 数据库: `' . C ( "DB_NAME" ) . '`' . $this->ds;
		$value .= '--' . $this->ds;
		$value .= '-- -------------------------------------------------------';
		$value .= $this->ds . $this->ds;
		return $value;
	}
	/**
	 * 插入表结构
	 *
	 * @param unknown_type $table        	
	 * @return string
	 */
	private function _insert_table_structure($table) {
		$sql = '';
		$sql .= "--" . $this->ds;
		$sql .= "-- 表的结构" . $table . $this->ds . "--" . $this->ds;
		$M = M ();
		// 如果存在则删除表
		$sql .= "DROP TABLE IF EXISTS `" . $table . '`' . $this->sqlEnd . $this->ds;
		// 获取详细表信息
		$res = $M->query ( 'SHOW CREATE TABLE `' . $table . '`' );
		$sql .= $res [0] ["Create Table"];
		$sql .= $this->sqlEnd . $this->ds;
		// 加上
		$sql .= $this->ds;
		$sql .= "--" . $this->ds;
		$sql .= "-- 转存表中的数据 " . $table . $this->ds;
		$sql .= "--" . $this->ds;
		$sql .= $this->ds;
		return $sql;
	}
	
	/**
	 * 插入语句构造
	 *
	 * @param string $table        	
	 * @return string
	 */
	private function _insert_record($table, $val) {
		// sql字段逗号分割
		
		// 循环每个子段下面的内容
		$comma = 0;
		$insert .= "INSERT INTO `" . $table . "` VALUES(";
		foreach ( $val as $v ) {
			$insert .= $comma == 0 ? "" : ",";
			$insert .= ("'" . mysql_escape_string ( $v ) . "'");
			$comma ++;
		}
		$insert .= ");" . $this->ds;
		
		return $insert;
	}
	
	/**
	 * 写入文件
	 *
	 * @param string $sql        	
	 * @param string $filename        	
	 * @param string $dir        	
	 * @return boolean
	 */
	private function _write_file($sql, $filename, $dir) {
		
		// 创建目录
		if (! is_dir ( $dir )) {
			mkdir ( $dir, 0777, true );
		}
		$re = true;
		if (! @$fp = fopen ( $dir . "/" . $filename, "w+" )) {
			$re = false;
			$msg .= "打开文件失败！";
		}
		if (! @fwrite ( $fp, $sql )) {
			$re = false;
			$msg .= "写入文件失败，请文件是否可写";
		}
		if (! @fclose ( $fp )) {
			$re = false;
			$msg .= "关闭文件失败！";
		}
		return $re;
	}
	
	/**
	 * 将sql导入到数据库（普通导入）
	 *
	 * @param string $sqlfile        	
	 * @return boolean
	 */
	private function _import($sqlfile) {
		// sql文件包含的sql语句数组
		$sqls = array ();
		$f = fopen ( $sqlfile, "rb" );
		// 创建表缓冲变量
		$create_table = '';
		while ( ! feof ( $f ) ) {
			// 读取每一行sql
			$line = fgets ( $f );
			// 这一步为了将创建表合成完整的sql语句
			// 如果结尾没有包含';'(即为一个完整的sql语句，这里是插入语句)，并且不包含'ENGINE='(即创建表的最后一句)
			if (! preg_match ( '/;/', $line ) || preg_match ( '/ENGINE=/', $line )) {
				// 将本次sql语句与创建表sql连接存起来
				$create_table .= $line;
				// 如果包含了创建表的最后一句
				if (preg_match ( '/ENGINE=/', $create_table )) {
					// 执行sql语句创建表
					$this->_insert_into ( $create_table );
					// 清空当前，准备下一个表的创建
					$create_table = '';
				}
				// 跳过本次
				continue;
			}
			// 执行sql语句
			$this->_insert_into ( $line );
		}
		fclose ( $f );
		return true;
	}
	// 插入单条sql语句
	private function _insert_into($sql) {
		$M = M ();
		if (! $M->query ( trim ( $sql ) )) {
			$msg .= mysql_error ();
			return false;
		}
	}
	// 锁定数据库，以免备份或导入时出错
	private function lock($tablename, $op = "WRITE") {
		$M = M ();
		if ($M->query ( "lock tables " . $tablename . " " . $op ))
			return true;
		else
			return false;
	}
	
	// 解锁
	private function unlock() {
		$M = M ();
		if ($M->query ( "unlock tables" ))
			return true;
		else
			return false;
	}
	}
